package com.jpl.seminar.ui.module.report;

import java.util.List;

import com.jpl.seminar.model.Registration;
import com.jpl.seminar.ui.module.registration.ModelPropertiesConstant;
import com.vaadin.data.Property;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Component;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.Table;

public class ReportTable extends Table {
	private static final long serialVersionUID = 1L;

	private BeanItemContainer<Registration> container;

	public ReportTable() {
		setWidth("50%");

		this.container = new BeanItemContainer<Registration>(Registration.class);
		setContainerDataSource(this.container);

		addGeneratedColumn("DELETE", new ActionColumnGenerator());

		setVisibleColumns(new String[] { ModelPropertiesConstant.REGISTRATION_COMPANY_FIELD, ModelPropertiesConstant.REGISTRATION_COUNTRY_FIELD,
				ModelPropertiesConstant.REGISTRATION_PARTICIPANTS_FIELD, "DELETE" });

		setColumnHeaders(new String[] { "Company", "Country", "# part", "-" });

		setColumnReorderingAllowed(false);
		setSelectable(true);

		setColumnWidth("DELETE", 40);
		setColumnAlignment("DELETE", Table.ALIGN_CENTER);
		setColumnExpandRatio(ModelPropertiesConstant.REGISTRATION_COMPANY_FIELD, 0.6f);
		setColumnExpandRatio(ModelPropertiesConstant.REGISTRATION_COUNTRY_FIELD, 0.2f);

	}

	@Override
	protected String formatPropertyValue(Object rowId, Object colId, Property property) {
		if (colId.equals(ModelPropertiesConstant.REGISTRATION_PARTICIPANTS_FIELD)) {
			Registration registration = (Registration) rowId;
			return String.valueOf(registration.getParticipants().size());
		}
		return super.formatPropertyValue(rowId, colId, property);
	}

	public void setRegistrations(List<Registration> registrations) {
		this.container.removeAllItems();
		this.container.addAll(registrations);
	}

	class ActionColumnGenerator implements ColumnGenerator {

		private static final long serialVersionUID = 1L;

		@Override
		public Component generateCell(Table source, Object itemId, Object columnId) {
			Embedded result = new Embedded();
			result.setType(Embedded.TYPE_IMAGE);
			result.setSource(new ThemeResource("icons/delete.png"));
			result.setWidth("16px");
			result.setHeight("16px");
			return result;
		}
	}

}
